package com.allm.ai.api.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ErrorResponse> handleBusinessException(BusinessException ex) {
        ErrorResponse error = new ErrorResponse(ex.getCode(), ex.getMessage());
        return ResponseEntity.status(HttpStatus.valueOf(ex.getHttpStatus())).body(error);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleException(Exception ex) {
        // 添加详细的错误日志
        log.error("Unhandled exception occurred", ex);
        log.error("Exception class: {}", ex.getClass().getName());
        log.error("Exception message: {}", ex.getMessage());
        if (ex.getCause() != null) {
            log.error("Caused by: {} - {}", ex.getCause().getClass().getName(), ex.getCause().getMessage());
        }

        ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred: " + ex.getMessage());
        return ResponseEntity.internalServerError().body(error);
    }
}
